package com.bs.coregamelibrary.protocolbuffer.codec.encode;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.MessageLite;
import com.google.protobuf.MessageLiteOrBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import java.io.IOException;
import java.util.List;
import static io.netty.buffer.Unpooled.*;

/**
 *
 * @author dungpt
 */
public class ProtobufEncoder extends MessageToMessageEncoder<MessageLiteOrBuilder> {

    @Override
    protected void encode(ChannelHandlerContext ctx, MessageLiteOrBuilder msg, List<Object> out) throws Exception {
        MessageLite messageLite = null;
        if (msg instanceof MessageLite) {
            messageLite = (MessageLite) msg;
        } else if (msg instanceof MessageLite.Builder) {
            messageLite = ((MessageLite.Builder) msg).build();
        }

        if (messageLite != null) {
            try {
                final byte[] convertedByteArray = new byte[messageLite.getSerializedSize()];
                final CodedOutputStream outputStream = CodedOutputStream.newInstance(convertedByteArray);
                messageLite.writeTo(outputStream);
                outputStream.checkNoSpaceLeft();

                out.add(wrappedBuffer(convertedByteArray));
            } catch (IOException e) {
                throw new RuntimeException("Serializing to a byte array threw an IOException "
                        + "(should never happen).", e);
            }
        }
    }
}
